package com.pxx.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxx.common.utils.PageResult;
import com.pxx.item.mapper.TbSkuMapper;
import com.pxx.item.mapper.TbSpuDetailMapper;
import com.pxx.item.mapper.TbStockMapper;
import com.pxx.item.pojo.*;
import com.pxx.item.service.TbBrandService;
import com.pxx.item.service.TbCategoryService;
import com.pxx.item.service.TbSpuService;
import com.pxx.item.mapper.TbSpuMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
* @author Yoo19
* @description 针对表【tb_spu(spu表，该表描述的是一个抽象性的商品，比如 iphone8)】的数据库操作Service实现
* @createDate 2025-06-27 08:10:48
*/
@Service
public class TbSpuServiceImpl extends ServiceImpl<TbSpuMapper, TbSpu>
    implements TbSpuService{
    @Autowired
    private TbSpuMapper tbSpuMapper;
    @Autowired
    private TbCategoryService tbCategoryService;
    @Autowired
    private TbBrandService tbBrandService;
    @Autowired
    private TbSpuDetailMapper tbSpuDetailMapper;
    @Autowired
    private TbSkuMapper tbSkuMapper;
    @Autowired
    private TbStockMapper tbStockMapper;

    @Override
    public PageResult<SpuBo> querySpuBoByPage(Integer page, Integer rows, String key, Boolean saleable) {
        QueryWrapper<TbSpu> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.like("title",key);
        }
        queryWrapper.eq("saleable",saleable);
        //分页查询
        Page<TbSpu> tbSpuPage = new Page<>(page,rows);
        Page<TbSpu> spuPage = tbSpuMapper.selectPage(tbSpuPage,queryWrapper);
        //处理数据的封装
        ArrayList<SpuBo> spuBos = new ArrayList<>();
        //查询对应的商品分类的id的名称以及品牌的名称
        if(!CollectionUtils.isEmpty(spuPage.getRecords())){
            spuPage.getRecords().forEach(spu ->{
                SpuBo spuBo = new SpuBo();
                BeanUtils.copyProperties(spu,spuBo);
                //查询商品分类的名称 id1 id2 id3
                List<String> names = tbCategoryService.queryNamesByIds(Arrays.asList(spu.getCid1(),spu.getCid2(),spu.getCid3()));
                //拼接数据  手机\手机通讯\手机
                spuBo.setCname(StringUtils.join(names,"/"));

                //查询品牌名称
                TbBrand tbBrand = tbBrandService.queryNamesById(spu.getBrandId());
                if(tbBrand != null){
                    spuBo.setBname(tbBrand.getName());
                }else {
                    spuBo.setBname("未知");
                }


                spuBos.add(spuBo);
            });
        }
        return new PageResult<>(spuPage.getTotal(),spuPage.getPages(),spuBos);
    }

    /**
     * 添加商品
     * @param spuBo
     */
    @Override
    public void addGoods(SpuBo spuBo) {
        //添加到spu中
            //初始化
        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());
        //添加数据到spu中
        tbSpuMapper.insert(spuBo);

        //添加关联数据到spu_detail
        TbSpuDetail spuDetail = spuBo.getSpuDetail();
        //吧spu中的主键ID赋值给spuDatil表中
        spuDetail.setSpuId(spuBo.getId());
        tbSpuDetailMapper.insert(spuDetail);

        //添加数据到sku中
        List<TbSku> skus = spuBo.getSkus();
        if(!CollectionUtils.isEmpty(skus)){
            for (TbSku sku : skus) {
                //设置sku中的spuid
                sku.setSpuId(spuBo.getId());
                sku.setCreateTime(new Date());
                sku.setLastUpdateTime(spuBo.getCreateTime());

                //添加数据到sku中
                tbSkuMapper.insert(sku);
                //添加数据到stock
                TbStock tbStock = new TbStock();
                tbStock.setSkuId(sku.getId());
                tbStock.setStock(sku.getStock());
                tbStock.setSeckillStock(0);
                tbStock.setSeckillTotal(0);
                tbStockMapper.insert(tbStock);
            }
        }

    }

    /**
     * 根据spuId查询SpuDetail
     * @param spuId
     * @return
     */
    @Override
    public TbSpuDetail querySpuDetailBySpuId(Long spuId) {
        //根据spuid查询spudetail
        return tbSpuDetailMapper.selectById(spuId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateGoods(SpuBo spuBo) {
            //先删除在添加

        //删除spu
        tbSpuMapper.deleteById(spuBo.getId());
        //删除SpuDetail
        tbSpuDetailMapper.deleteById(spuBo.getId());

        //通过spuId查询skus集合
        List<TbSku> skuList = tbSkuMapper.selectList(new QueryWrapper<TbSku>().lambda().eq(TbSku::getSpuId, spuBo.getId()));
        for (TbSku sku : skuList) {
            tbSkuMapper.deleteById(sku.getSpuId());
        }

        tbSkuMapper.delete(new QueryWrapper<TbSku>().lambda().eq(TbSku::getSpuId,spuBo.getId()));

        //添加到spu中
        //初始化
        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());
        //添加数据到spu中
        tbSpuMapper.insert(spuBo);

        //添加关联数据到spu_detail
        TbSpuDetail spuDetail = spuBo.getSpuDetail();
        //吧spu中的主键ID赋值给spuDatil表中
        spuDetail.setSpuId(spuBo.getId());
        tbSpuDetailMapper.insert(spuDetail);

        //添加数据到sku中
        List<TbSku> skus = spuBo.getSkus();
        if(!CollectionUtils.isEmpty(skus)) {
            for (TbSku sku : skus) {
                //设置sku中的spuid
                sku.setSpuId(spuBo.getId());
                sku.setCreateTime(new Date());
                sku.setLastUpdateTime(spuBo.getCreateTime());

                //添加数据到sku中
                tbSkuMapper.insert(sku);
                //添加数据到stock
                TbStock tbStock = new TbStock();
                tbStock.setSkuId(sku.getId());
                tbStock.setStock(sku.getStock());
                tbStock.setSeckillStock(0);
                tbStock.setSeckillTotal(0);
                tbStockMapper.insert(tbStock);
            }
        }
    }


}




